package net.zjitc.controller;

import net.zjitc.pojo.*;
import net.zjitc.service.CartService;
import net.zjitc.service.CategoryService;
import net.zjitc.service.OrderService;
import net.zjitc.service.impl.CartServiceImpl;
import net.zjitc.service.impl.CategoryServiceImpl;
import net.zjitc.service.impl.OrderServiceImpl;
import net.zjitc.utils.CommonUtils;
import net.zjitc.utils.dispacher.URLMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/12/13.
 */
public class UserOrder {
    OrderService orderService = new OrderServiceImpl();
    CartService cartService = new CartServiceImpl();
    CategoryService service = new CategoryServiceImpl();
    @URLMapping(url = "/creatOrder")
    public String creatOrder(HttpServletRequest request, HttpServletResponse response){
        List<Category> clist = service.findAll();
        request.setAttribute("clist",clist);
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            user = new User();
            user.setUid(user.getUid());
            user.setUsername("aaa");
            user.setAddr("家里");
            user.setPhone("110");
        }
        Order order = new Order();
        order.setOid(CommonUtils.uuid());
        order.setAddr(user.getAddr());
        order.setPhone(user.getPhone());
        order.setName(user.getName());
        order.setState(0);
        order.setUser(user);
        order.setOrdertime(CommonUtils.dateToString(new Date()));
        List<CartItem> _cartItemList = cartService.findByUid(user.getUid());
        if(_cartItemList==null){
            return "/WEB-INF/user/order.jsp";
        }
        List<Orderitem> orderitemList = new ArrayList<Orderitem>();
        double total = 0.0;
        for(CartItem item :_cartItemList){
            Orderitem orderitem = new Orderitem();
            orderitem.setOrder(order);
            orderitem.setProduct(item.getProduct());
            orderitem.setOsatate(0);
            orderitem.setCount(item.getQuantity());
            orderitem.setSubtotal(item.getProduct().getShop_price()*item.getQuantity());
            total = total+item.getProduct().getShop_price()*item.getQuantity();
            orderitemList.add(orderitem);
        }
        order.setOrderitemList(orderitemList);
        order.setTotal(total);
        int count = orderService.add(order);
        cartService.deleteByUid(user.getUid());
        request.setAttribute("order",order);
        return "/WEB-INF/user/order.jsp";
    }
}
